package ru.vsu.cs.kis.elections.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import ru.vsu.cs.kis.elections.GeneralConsts;
import ru.vsu.cs.kis.elections.server.db.DBConnector;

public class ServerThread implements Runnable {

	private static ServerThread inner = null;

	private static boolean isActive = false;

	private static ServerSocket server = null;

	private static ExecutorService service= null;
	
	static {
		DBConnector.connect();
	}

	private ServerThread() {
		try {
			isActive = true;
			server = new ServerSocket(GeneralConsts.PORT);
			service=Executors.newCachedThreadPool(); 
			Thread thr = new Thread(this);
			thr.start();
		} catch (IOException ex) {
			ex.printStackTrace(System.err);
		}
	}	
	
	@Override
	public void run() {
		System.out.print("server start \n");
		while (isActive) {
			try {
				Socket socket = server.accept();
				ServerTask newTask = new ServerTask(socket);
				service.execute(newTask);
			} catch (IOException ex) {
				ex.printStackTrace(System.err);
			}
		}
	}

	public static ServerThread runServer() {
		if (inner == null) {
			inner = new ServerThread();
			return inner;
		}
		return inner;
	}

	public static void stopServer() {
		service.shutdown();
		isActive = false;
		System.out.print("server stop \n");
	}

}
